import 'package:myapp/api/online_repository.dart';
import 'package:myapp/bean/article.dart';
import 'package:myapp/bean/category.dart';
import 'package:myapp/globle/const.dart';
import 'package:myapp/view_model/base_model.dart';

class SystemPageModel extends BaseModel {
  List<Article> _articles = [];
  bool _isLoadMore = false;

  List<Article> get getArticles => _articles;

  bool get isLoadMore => _isLoadMore;

  int get chooseId => _id;

  int _page = 0;

  int _id = -1;

  List<Category> _allCategories = [];

  List<Category> _subCategories = [];

  List<Category> getTag(index) => _subCategories[index].children;

  List<Category> get getArticleCategories => _allCategories;

  loadArticleCategories(Function(List<Category> categorys) f) async {
    if (_allCategories.isEmpty) {
      var categories = await OnlineRepository.getArticleCategories();
      _allCategories.addAll(categories);
      f(categories);
      notifyListeners();
    }
  }

  refresh() async {
    _page = 0;
    _articles.clear();
    if (_id != -1) {
      var articles = await OnlineRepository.getArticleListByCid(_page, _id);
      _articles.addAll(articles);
    }
    _isLoadMore = _articles.length >= Const.PAGE_NUM;
    notifyListeners();
  }

  loadMore() async {
    _page++;
    if (_id != -1) {
      var articles = await OnlineRepository.getArticleListByCid(_page, _id);
      _articles.addAll(articles);
      _isLoadMore = articles.length >= Const.PAGE_NUM;
    } else {
      _isLoadMore = false;
    }
    notifyListeners();
  }

  chooseTag(id) {
    _id = id;
  }
}
